//create by 2017年10月4日16:36:45 lwy


var ifComment = 'false';
var ifSlide = 'true';
var ifDetail = 'false';
var topHeight = 44;
var getHeight = '';
var collectionsId = '';
var token = getItem('token');
var userId = GetQueryString('userId');
var ifChoose = 0;
var goodsTypeValue = GetQueryString('goodsTypeValue');
if(goodsTypeValue==2){
    //积分抽奖
    $('.buy').html('立即参与')
    $('#progess').show();
    $('.integral_price').show();
}else{
    $('.price_box').show();
}
var periodis = '';
if (userId == null || userId == undefined || userId == "") {
} else {
    setItem('userId')
}
var liHeight = $('body').width() * 0.31 - 22;
$(function () {
    doGoods();
})


var goodsId = GetQueryString('goodsId');
var specification;
var isValueAddedServices;

//商品详情
function doGoods() {
    $.ajax({
        url: '/integralGoods/detail.json',
        dataType: 'json',
        data: {
            id: goodsId,
            token: token,
            goodsTypeValue:goodsTypeValue,
            companyCode: getItem('companyCode'),
        },
        type: 'post',
        beforeSend: function () {
            $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
        },
        success: function (data) {
            $('.loading2').hide();
            if (data.code == 1) {
                var goodsData = data.datas;
                var mainImg = data.datas.mainImg.split(',');
                if (mainImg.length > 1) {
                    for (var n = 0; n < mainImg.length - 1; n++) {
                        $('<div class="swiper-slide">' +
                            '<a class="banner">' +
                            '<img src="' + mainImg[n] + '">' +
                            '</a></div>').appendTo($('#banner'));
                    }
                } else {
                    for (var n = 0; n < mainImg.length; n++) {
                        $('<div class="swiper-slide">' +
                            '<a class="banner">' +
                            '<img src="' + mainImg[n] + '">' +
                            '</a></div>').appendTo($('#banner'));
                    }
                }

                $('#spe_img').attr('src', mainImg[0]);
                //轮播图
                var mySwiper = new Swiper('.swiper-container4', {
                    loop: false,
                    autoplay: 5000,
                    pagination: '.swiper-pagination4',
                    paginationClickable: true,
                })
                specification = goodsData.isSpecification;
                periodis = goodsData.periodsId;
                goodsId = goodsData.id;
                $(goodsData.detailsImg).appendTo($('#detailBox1'));
                $('#goodsName').html(goodsData.name);
                $('.price').html(data.datas.unitIntegral+'<small> 积分</small>');
                $('#memberPrice').html(goodsData.unitIntegral+'<small> 积分</small>');
                $('.integral_price').html('总需'+data.datas.totalNum+'<span class="quondam">剩余<b>'+(data.datas.totalNum-data.datas.nowNum)+'</b></span>')
                var progressbar1 = mui('#progess');
                var progressBar = goodsData.baifen;
                mui(progressbar1).progressbar().setProgress(progressBar)
                doSpe();
            }
        }
    })
}

var propertiesId = '';
var param;
var propertiesName;
var speLength = 0;

//获取规格
function doSpe() {
    //无规格商品
    if (!specification) {
        $('<div class="detail_count_title">' +
            '<span>数量</span>' +
            '<span class="choose_count">' +
            '<span class="decreace"></span' +
            '><input type="text"  class="count" style="width: 60px;" value="1"' +
            '><span class="add"></span>' +
            '</span>' +
            '</div>').insertBefore($('#appreciation_box'));
        //detail();
    } else {
        //规格商品
        $.ajax({
            url: '/specificationC/getSpecification.json',
            dataType: 'json',
            data: {
                goodid: GetQueryString('goodsId'),
                companyCode: getItem('companyCode'),
            },
            type: 'post',
            success: function (data) {
                var speData = data.datas;
                speLength = speData.length;
                for (var i = 0; i < speData.length; i++) {
                    $('<div class="detail_small_box" id="detail_spe' + speData[i].id + '"></div>').insertBefore($('#appreciation_box'));
                    $('<div class="detail_title">' + speData[i].name + '</div>').appendTo($('#detail_spe' + speData[i].id + ''));
                    $('<div class="detail_spe mui-clearfix" id="detailOne_spe' + speData[i].id + '" bigId="' + speData[i].id + '"></div>').appendTo($('#detail_spe' + speData[i].id + ''));
                    for (var b = 0; b < speData[i].data.length; b++) {
                        $('<div class="spe-one" parent="' + speData[i].id + '" son="' + speData[i].data[b].id + '" id="' + speData[i].data[b].id + '">' + speData[i].data[b].content + '</div>').appendTo($('#detailOne_spe' + speData[i].id + ''));
                    }
                }
                $('<div class="detail_count_title">' +
                    '<span>数量</span>' +
                    '<span class="choose_count">' +
                    '<span class="decreace">-</span' +
                    '><input type="text" class="count"  value="1"' +
                    '><span class="add"></span>' +
                    '</span>' +
                    '</div>').insertBefore($('#appreciation_box'));

                //获取有效id
                $.ajax({
                    url: '/specificationContentC/getSpecificationContentid.json',
                    dataType: 'json',
                    data: {
                        goodid: goodsId,
                        companyCode: getItem('companyCode'),
                    },
                    type: 'post',
                    success: function (data) {
                        if (data.code == 1) {
                            param = data.datas[data.datas.length - 1];
                            var delPAram = param.trim('{').trim('}');
                            var actParam = delPAram.split(',');
                            for (var g = 0; g < actParam.length; g++) {
                                var actParam2 = actParam[g].split(':');
                                $('#' + actParam2[1] + '').addClass('spe_act');
                                $('#' + actParam2[1] + '').attr('ifAct', 'true');
                            }
                            doValid(delPAram);
                            $.ajax({
                                url: '/goodSpecificationC/getGoodSpecification.json',
                                dataType: 'json',
                                data: {
                                    goodid: GetQueryString('goodsId'),
                                    propertiesid: delPAram,
                                    companyCode: getItem('companyCode'),
                                },
                                type: 'post',
                                success: function (data) {
                                    //获取规格库存，图片
                                    if (data.code == 1) {
                                        $('#spe_img').attr('src', data.datas.image);
                                        $('.price').html('¥' + data.datas.memberPrice);
                                        propertiesId = data.datas.id;
                                        priceSpecificationId = data.datas.id;
                                        detail();
                                        doPrice();
                                        propertiesName = data.datas.propertiesName;
                                        if (data.datas.stages != 0) {
                                            var stagesLength = data.datas.stages.length;
                                            $('.stage_periods').html(data.datas.stages[stagesLength - 1].instalmentAmount + 'x' + data.datas.stages[stagesLength - 1].periods + ' 期');
                                            $('#stages').show();
                                            doStage(data.datas.stages)
                                        } else {
                                            $('#stages').hide();
                                        }
                                        $('#marketprice').html('<span>市场价' + data.datas.maketPirce + '</span>');
                                        $('#memberprice').html('¥' + data.datas.memberPrice);
                                        //获取已选择字符串拼接，待测试
                                        var speStr = '';
                                        $('.spe_act').each(function () {
                                            speStr += $(this).html() + ', ';
                                        })
                                        speStr += '* ' + $('.count').val();
                                        $('#choose').html('已选');
                                        $('#choose_detail').html(propertiesName + '* ' + $('.count').val());
                                    }
                                    if (data.code == 0) {
                                        //thisDiv.find('.detail_spe .spe-one:nth-of-type(1)').removeClass('spe_act');
                                        //thisDiv.find('.detail_spe .spe-one:nth-of-type(1)').attr('ifAct', 'false');
                                    }
                                }
                            })
                        }
                    }
                })
                // $('.detail_spe').each(function () {
                //     var thisDiv = $(this);
                //     thisDiv.find('.spe-one:nth-of-type(1)').addClass('spe_act');
                //     thisDiv.find('.spe-one:nth-of-type(1)').attr('ifAct', 'true');
                //     var o = $("div[ifAct='true']");
                //     param = '';
                //     for (var i = 0; i < o.length; i++) {
                //         param += $(o.get(i)).attr('parent') + ':' + $(o.get(i)).attr('son');
                //         if (i != o.length - 1) {
                //             param += ','
                //         }
                //     }
                //
                // })
                //选择加入购物车
                $('.spe-one').click(function () {
                    var this2 = $(this);
                    //如果此规格包含虚线
                    if ($(this).hasClass('spe_noChoose')) {
                        this2.siblings().removeClass('spe_act').removeClass('spe_noChoose').addClass('spe_defalut');
                        this2.siblings().attr('ifAct', 'false');
                        this2.removeClass('spe_noChoose').removeClass('spe_defalut').addClass('spe_act');
                        this2.attr('ifAct', 'true');
                        this2.parent().parent().siblings().find('.spe-one').removeClass('spe_noChoose').removeClass('spe_act').addClass('spe_defalut');
                        this2.parent().parent().siblings().find('.spe-one').attr('ifAct', 'false');
                    } else {
                        this2.removeClass('spe_noChoose').removeClass('spe_defalut').addClass('spe_act');
                        this2.attr('ifAct', 'true');
                        this2.siblings().attr('ifAct', 'false');
                        this2.siblings().removeClass('spe_noChoose').removeClass('spe_act').addClass('spe_defalut');
                        this2.parent().parent().siblings().find('.spe-one').each(function () {
                            if ($(this).hasClass('spe_noChoose')) {
                                $(this).removeClass('spe_noChoose').addClass('spe_defalut');
                            }
                        })
                    }

                    var o2 = $("div[ifAct='true']");
                    var param2 = '';
                    for (var l = 0; l < o2.length; l++) {
                        param2 += $(o2.get(l)).attr('parent') + ':' + $(o2.get(l)).attr('son');
                        if (l != o2.length - 1) {
                            param2 += ','
                        }
                    }
                    doValid(param2);

                    if (speLength == 2) {
                        if ($('div[ifact=true]').length == 2) {
                            dospeDetail();
                        }
                    } else if (speLength == 1) {
                        dospeDetail();
                    }
                    else if (speLength == 3) {
                        if ($('div[ifact=true]').length == 3) {
                            dospeDetail();
                        }
                    }

                })

                function dospeDetail() {
                    var o = $("div[ifAct='true']");
                    param = '';
                    for (var i = 0; i < o.length; i++) {
                        param += $(o.get(i)).attr('parent') + ':' + $(o.get(i)).attr('son');
                        if (i != o.length - 1) {
                            param += ','
                        }
                    }
                    $.ajax({
                        url: '/goodSpecificationC/getGoodSpecification.json',
                        dataType: 'json',
                        data: {
                            goodid: GetQueryString('goodsId'),
                            propertiesid: param,
                            companyCode: getItem('companyCode'),
                        },
                        type: 'post',
                        beforeSend: function () {
                            if (speLength == 2) {
                                if ($('div[ifact=true]').length == 2) {
                                    $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                                }
                            } else if (speLength == 1) {
                                $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                            }
                            else if (speLength == 3) {
                                if ($('div[ifact=true]').length == 3) {
                                    $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                                }
                            }
                        },
                        success: function (data) {
                            //获取规格库存，图片
                            if (data.code == 1) {
                                $('.loading2').hide();
                                $('#spe_img').attr('src', data.datas.image);
                                $('.price').html('¥' + data.datas.memberPrice);
                                propertiesId = data.datas.id;
                                priceSpecificationId = data.datas.id;
                                detail();
                                doPrice();
                                propertiesName = data.datas.propertiesName;
                                if (data.datas.stages != 0) {
                                    var stagesLength = data.datas.stages.length;
                                    $('.stage_periods').html(data.datas.stages[stagesLength - 1].instalmentAmount + 'x' + data.datas.stages[stagesLength - 1].periods + ' 期');
                                    $('#stages').show();
                                    doStage(data.datas.stages)
                                } else {
                                    $('#stages').hide();
                                }
                                $('#marketprice').html('<span>市场价' + data.datas.maketPirce + '</span>');
                                $('#memberprice').html('¥' + data.datas.memberPrice);
                            }
                            if (data.code == 0) {
                                $('.loading2').hide();
                                if (speLength == 2) {
                                    if ($('div[ifact=true]').length == 2) {
                                        mui.toast(data.msg);
                                        return;
                                    }
                                }
                                if (speLength == 3) {
                                    if ($('div[ifact=true]').length == 3) {
                                        mui.toast(data.msg);
                                        return;
                                    }
                                }
                                if (speLength == 1) {
                                    mui.toast(data.msg);
                                    return;
                                }
                            }
                        }
                    })
                }
            }
        })
    }
}


var ifClickCart = 'false';
var ifClickBuy = 'false';

$(document).ready(function () {
    //添加
    var count = 1;
    $(document).on('click', '.add', function () {
        count++;
        if (count > 1) {
            $('.decrease').css('color', '#49c9bb');
        }
        $('.count').val(count);
    })
    //减少
    $(document).on('click', '.decreace', function () {
        count--;
        if (count < 1) {
            count = 1;
            $('.decreace').css('color', '#bfbcc0');
        }
        if (count > 1) {
            $('.decreace').css('color', '#49c9bb');
        }
        $('.count').val(count);
    })
    //输入产品数量
    $("body").on('change', '.count', function () {
        //判断输入数量是否为空或小于1
        if ($('.count').val() == '' || $('.count').val() == NaN || $('.count').val() < 1 || $('.count').val() == null || $('.count').val() == undefined) {
            $('.count').val(1);
        }
        count = parseInt($('.count').val());
        if (count > 1) {
            $('.decrease').css('color', '#49c9bb');
        }
    })
})

//确定
$('.spe_certain').click(function () {

    $('#choose').html('已选');
    $('#choose_detail').html('数量' + $('.count').val());
    ifChoose = 1;
    if (ifClickCart == 'true') {
        addCart();
        return;
    }
    if (ifClickBuy == 'true') {
        ifChoose = 0;
        buy();
        return;
    }


    //获取已选择字符串拼接
    var speStr = '';
    $('.spe_act').each(function () {
        speStr += $(this).html() + ', ';
    })
    speStr += '数量' + $('.count').val();
    $('.specification_box').hide();
    $('.float-box').show();
    $('.choose-sku').html('<span class="choose">已选择</span><span class="choose-yet">' + speStr + '</span>');

})

//点击加入购物车
$('.add-cart').click(function () {
    ifClickCart = 'true';
    ifClickBuy = 'false';
    getSpe();
})

function getSpe() {
    if (ifChoose == 0) {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
        $('.specification_box').show();
        $('.specification_box').css({'opacity': '1', 'top': '0', 'height': '100%', 'visibility': 'visible'})
        $('body,html,.mui-content').css({'height': '100%', 'overflow': 'hidden'});
        $('.float-box').hide();

    }else{
        if (ifClickCart == 'true') {
            addCart();
            return;
        }
        if (ifClickBuy == 'true') {
            buy();
            return;
        }
    }
}


//加入购物车
function addCart() {
    $.ajax({
        url: '/ShoppingCartC/addUserShoppingCart.json',
        dataType: 'json',
        data: {
            goodsId: goodsId,
            count: $('.count').val(),
            token: getItem('token'),
            companyCode: getItem('companyCode'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                //获取已选择字符串拼接，待测试
                var speStr = '';
                $('.spe_act').each(function () {
                    speStr += $(this).html() + ', ';
                })
                speStr += '数量' + $('.count').val();
                $('.specification_box').hide();
                $('.float-box').show();
                mui.toast('加入购物车成功');
                propertiesId = '';
                $('.spe-one').removeClass('spe_act');
                $('.spe-one').attr('ifact', 'false');
                $('#choose').html('已选');
                $('#choose_detail').html(speStr);
            }
            if (data.code == 0) {
                mui.toast(data.msg);
                propertiesId = '';
                return;
            }
            if (data.code == -1) {
                window.location.href = "login.html";
            }
        }
    })
}

//立即购买
$('.buy').click(function () {
    ifClickBuy = 'true';
    ifClickCart = 'false';
    getSpe();
})

function buy() {
    var orderInfor = {};
    orderInfor.goodsId = goodsId;
    orderInfor.num = $('.count').val();
    orderInfor.periodis = periodis;
    orderInfor.goodsTypeValue = goodsTypeValue;
    orderInfor = JSON.stringify(orderInfor);
    removeItem('deliveryType');
    removeItem('payType');
    removeItem('addressId');
    window.location.href = "integral_confirmOrder.html?type=1&orderInfor=" + orderInfor
}


//标题点击
document.getElementById('detail').addEventListener('tap', function () {
    ifComment = 'false';
    ifSlide = 'false';
    $('#goodsBox1,#detailBox').show();
    $('#commentBox').hide();
    $('#detail').addClass('act');
    $('#detail').find('span').show();
    $('#goods,#comment').removeClass('act');
    $('#goods,#comment').children().hide();
    mui('.mui-scroll-wrapper2').scroll().reLayout();//重新计算布局值，最大滚动的高度等等
    var y = 0;
    var current_top = mui('.mui-scroll-wrapper2').scroll().y;
    y = $('#detailBox').offset().top; //计算位置
    y = parseInt(current_top - y);
    if (y > 0)
        y = -y;
    mui('#refreshContainer').scroll().scrollTo(0, parseInt(y + 44), 0);
    //mui('#refreshContainer').scroll().scrollTo(-($('#detailBox').offset().top),0);
    //scroll2($('#detailBox').offset().top);
    ifSlide = 'true';
})
document.getElementById('goods').addEventListener('tap', function () {
    ifComment = 'false';
    ifSlide = 'false';
    $('#goodsBox1,#detailBox').show();
    $('#commentBox').hide();
    $('#goods').addClass('act');
    $('#goods').find('span').show();
    $('#detail,#comment').removeClass('act');
    $('#detail,#comment').children().hide();
    mui('#refreshContainer').scroll().scrollTo(0, 0, 0);
    ifSlide = 'true';
})

function scroll2(e) {
    mui.scrollTo(e, 200);
}

//更多按钮
$('#share2,#share,.more').click(function () {
    //分享到朋友圈
    if (is_weixn()) {
        mui.alert('请点击右上角分享')
    } else {
        mui.alert('请在微信中打开')
    }
})

var uip = document.getElementById("topPopover");
uip.style.position = "absolute";
$(".mui-backdrop").click(function () {
    $("#topPopover").hide();
    $(".mui-backdrop").hide();
});
mui('body').on('tap', '.mui-table-view-cell a', function () {
    document.location.href = this.href;
});


//规格盒子
document.getElementById('choose_box').addEventListener('tap', function () {
    $('#mui-scroll-wrapper').css('top', liHeight + 'px');
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    $('.specification_box').show();
    $('.specification_box').css({'opacity': '1', 'top': '0', 'height': '100%', 'visibility': 'visible'})
    $('body,html,.mui-content').css({'height': '100%', 'overflow': 'hidden'});
    $('.float-box').hide();
})


//规格盒子关闭
document.getElementById('colse_spe').addEventListener('tap', function () {
    //hideBox('.specification_box', 100);
    //$('#mui-scroll').css('transform','translate3d(0px, 0px, 0px) translateZ(0px)');
    $('.specification_box').hide();
    //$('.specification_box').css({'opacity':'0','top':'100%','height':'0','visibility':'hidden'})
    //$('body,html,.mui-content').css({'height': 'auto', 'overflow': 'auto'});
    $('.float-box').show();
})



function detail() {
    $('#detailBox2,#detailBox3').empty();
    $.ajax({
        url: '/ddmGoodsC/portalDetails2.json',
        dataType: 'json',
        data: {
            id: goodsId,
            goodSpecificationId: propertiesId,
            companyCode: getItem('companyCode'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                $(data.datas.parameter).appendTo($('#detailBox2'));
            }
        }
    })
}

//规格参数
mui('body').on('tap', '.parameter li', function () {
    $(this).addClass('par-active');
    $(this).siblings().removeClass('par-active');
    var showDiv = $(this).attr('showDiv');
    $('#' + showDiv + '').show();
    $('#' + showDiv + '').siblings().hide();
    $('.technical_support').show();
})

function getScrollTop() {
    //滚动条在Y轴上的滚动距离
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
}

//浏览器视口的高度
function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

//文档的总高度
function getScrollHeight() {
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
}


var scroll = mui('.mui-scroll-wrapper2').scroll();
document.querySelector('.mui-scroll-wrapper2').addEventListener('scroll', function (e) {
    var current_top = mui('.mui-scroll-wrapper2').scroll().y;
    var y = $('#detailBox').offset().top; //计算位置
    y = -y;
    if (ifSlide == 'true') {
        if (ifComment == 'false') {
            if (current_top < y) {
                $('#detail').addClass('act');
                $('#detail').find('span').show();
                $('#goods,#comment').removeClass('act');
                $('#goods,#comment').children().hide();
            } else {
                $('#goods').addClass('act');
                $('#goods').find('span').show();
                $('#detail,#comment').removeClass('act');
                $('#detail,#comment').children().hide();
            }
        }
    }
})


$('.link-qq').click(function () {
    if($('#QR-code').attr('src')==""||$('#QR-code').attr('src')==undefined||$('#QR-code').attr('src')==null){
        $.ajax({
            url:'/keFuC/getOne.json',
            dataType:'json',
            type:'post',
            data:{
                companyCode:getItem('companyCode')
            },
            success:function (data) {
                if(data.code==1){
                    $('#wxNum').html('微信号：'+data.datas.weChatNumber);
                    $('#QR-code').attr('src',data.datas.weChatCode);
                }
            }
        })
    }

    $('.QR-code').show();
    //window.location.href = "http://wpa.b.qq.com/cgi/wpa.php?ln=1&key=XzkzODE5MzgwMF80Njk1NzRfNDAwNjAxNjYwNl8yXw"
    document.getElementById('close').addEventListener('tap',function () {
        $('.QR-code').hide();
    })
})

mui('#mui-scroll-wrapper').scroll({
    deceleration: 0.0006, //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
});

mui('.mui-scroll-wrapper2').scroll({
    deceleration: 0.1, //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
    indicators: false
});

// mui('#top2').on('tap','a',function () {
//     window.location.href=$(this).attr('href');
//     //
//     // if (window.location.hash !== "") {
//     //     window.location.hash = "";
//     // }
//     // history.replaceState(null,'',location.pathname+location.search);
//     // scroll2($('#detailBox').offset().top)
//     return false;
// })

// document.getElementById('back').addEventListener('tap',function () {
//     // var url = window.location.href;
//     // if(url.indexOf('#')>0){
//     //
//     // }
// })